'use strict'
var socketIo = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};
exports.listen = function(serve){
  // 启动socketIo服务器,允许它搭载在已有的http服务器上
  io = socketIo.listen(serve);
  io.set('log level ',1);
  io.sockets.on('connection',function(sok){// 用户连接逻辑
    console.log('------------------ 有用户连接 ---------------------------');
    // 在用户连接上来时赋予其一个访客名
    guestNumber = assignGuestName(sok,guestNumber,nickNames,namesUsed);
    //在用户连接上来时将他放入Lobby聊天室中
    joinRoom(sok,'Lobby');
    // // 处理用户的消息,更名,以及创建聊天室和变更
    handleMessageBroadcasting(sok,nickNames);//消息
    handleNameChenageAttepts(sok,nickNames,namesUsed);//更名
    handleRoomJoining(sok);//创建聊天室或变更

    // /*用户发出请求时向其提供已经被占用的聊天室列表*/
    // sok.on('rooms',function(){
    //   sok.emit('rooms',io.sockets.manager.rooms);
    // });
    // // 定义用户断开连接后的清除逻辑
    // handleClientDisconnection(sok,nickNames,namesUsed);
  });

  // 分配聊天名称
  function assignGuestName(sok,guestNumber,nickNames,namesUsed){
    var name = 'Guest'+guestNumber;
    nickNames[sok.id] = name;
    sok.emit('nameResult',{success:true,name:name});
    namesUsed.push(name);
    return guestNumber+1;
  }
  // 分配聊天室
  function joinRoom(sok,room){
    sok.join(room);// 让用户进入房间
    currentRoom[sok.id] = room;//记录用户的当前房间
    sok.emit('joinResult',{room:room});
    // 让用户知道进入了新的房间
    sok.broadcast.to(room).emit('message',{text:nickNames[sok.id]+' has joined '+room+'.'});
    // 查找有多少用户在房间里
    // var usersInRoom = io.sockets.clients(room);
    // 如果房间不止一个人,则汇总下都是谁
    //将房间里其他用户的 汇总发送给这个用户
    // if(usersInRoom.length > 1){
    //   var usersInRoomSummary = 'Users currently in '+room+': ';
    //   for(var i in usersInRoom){
    //     var userSocketId =  usersInRoom[i].id;
    //     if(userSocketId != sok.id){
    //       if(i>0){
    //         usersInRoomSummary += ', ';
    //       }
    //       usersInRoomSummary += nickNames[userSocketId];
    //     }
    //   }
    // }

  }
  // 消息处理
  function handleMessageBroadcasting(sok){
    sok.on('message',function(message){
       sok.broadcast.to(message.room).emit('message',
        {text:nickNames[sok.id]+': '+message.text});
    });
  }
  // 更名处理
  function handleNameChenageAttepts(sok,nickNames,namesUsed){
    sok.on('nameAttempt',function(name){
      // 名称不能以Guest开头
      if(name.indexOf('Guest') == 0){
        sok.emit('nameResult',{success:false,message:'Names cannot begin with "GUest".'})
      } else if(namesUsed.indexOf(name) == -1){
        var previousName = nickNames[sok.id];
        var previousNameIndex = namesUsed.indexOf(previousName);
        namesUsed.push(name);
        nickNames[sok.id] = name;
        delete namesUsed[previousNameIndex];
        sok.emit('nameResult',{success:true,name:name});
        // 让用户知道进入了新的房间
        sok.broadcast.to(currentRoom[sok.id]).emit('message',{text:previousName+' is now known as '+name+'.'});
      } else {
        sok.emit('nameResult',{success:true,message:'That name is already in use'});
      }
    })
  }
  // 创建或更换聊天室处理
  function handleRoomJoining(sok){
    sok.on('join',function(room){
      sok.leave(currentRoom[sok.id]);
      joinRoom(sok,room.newRoom);
    })
  }
  // 断开连接处理
  function handleClientDisconnection(sok,guestNumber,nickNames,namesUsed){
    sok.on('disconnect',function(){
      var nameIndex = namesUsed.indexOf[sok.id];
      delete namesUsed[nameIndex];
      delete nickNames[sok.id];
    })
  }

}